<template>
  <!-- 添加考试 -->
  <el-drawer
    :visible="examDialogVisible"
    direction="btt"
    append-to-body
    size="100%"
    custom-class="drawer-box"
    :before-close="()=>{this.examDialogVisible = false}"
    v-loading="loading"
  >
    <el-container>
      <el-header style="padding-top: 10px;height: 100%">
        <el-form ref="form" :model="form" :rules="rules" :inline="true">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="试卷名称" prop="name">
                <el-input v-model="form.name"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="试卷分类" prop="cateId" v-if="!isMonth">
                <el-input placeholder="请选择分类" :value="current.name" type="text" readonly>
                  <template slot="suffix">
                    <el-button class="el-icon-edit" @click="checkSort" type="text">选择分类</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="选择分类" prop="cateId" v-if="isMonth">
                <el-input placeholder="请选择分类" :value="current.name" type="text" readonly>
                  <template slot="suffix">
                    <el-button class="el-icon-edit" @click="checkSort" type="text">选择分类</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="每次答题数" prop="everyTimeAnswNum" v-if="isMonth">
                <!--            <el-input-number controls-position="right" :min="1" v-model="form.dailyQuesCount"/>-->
                <el-input-number controls-position="right" :min="1" v-model="form.everyTimeAnswNum"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button
                class="el-icon-check"
                type="text"
                @click="onSubmit"
                style="color: #67C23A;font-size:24px;margin-left: 300px"
              />
              <el-button
                class="el-icon-close"
                type="text"
                @click="()=>{this.examDialogVisible = false}"
                style="color: #F56C6C;font-size: 24px"
              />
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="答题次数" prop="answUpperLimit" v-if="isMonth">
                <el-input-number controls-position="right" :min="1" v-model="form.answUpperLimit"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-radio-group v-model="form.answType" v-if="isMonth">
                  <el-radio-button :label="1">每日</el-radio-button>
                  <el-radio-button :label="2">每周</el-radio-button>
                  <el-radio-button :label="3">每月</el-radio-button>
                  <el-radio-button :label="4">间隔</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.answType == 4">
                <el-input-number controls-position="right" :min="1" v-model="form.intervalDay"/>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div>
                <el-checkbox v-if="isMonth" v-model="form.ischecked" @change="changeTime">选择时间段</el-checkbox>
              </div>
            </el-col>
            <el-col :span="8" v-if="form.ischecked === true">
              <el-form-item label="选择月份" prop="date" v-if="isMonth && form.answType == 3">
                <el-date-picker
                  v-model="form.date"
                  type="monthrange"
                  range-separator="至"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始月份"
                  end-placeholder="结束月份">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="date" v-if="isMonth && form.answType != 3">
                <el-date-picker
                  v-model="form.date"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  value-format="yyyy-MM-dd"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <hr style="margin: 0"/>
          <el-row :gutter="20" v-if="isMonth">
            <el-col :span="6">
              <el-form-item prop="quesRange">
                <el-radio-group v-model="form.quesRange">
                  <el-radio-button :label="0">指定题库</el-radio-button>
                  <el-radio-button :disabled="!form.ischecked" :label="1">指定试题</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>


        <el-dialog
          title="分类管理"
          :visible.sync="dialogFormVisible"
          :show-close="false"
          append-to-body
          width="30%"
        >
          <!--            v-if="paperCate"-->
          <paper-cate
            ref="paperCate"
            v-if="!isMonth"
            :setCurrent="setCurrent"
            :url="{
                                cateType: 1,
                                update:'/exam-admin/paper/cate/update',
                                save:'/exam-admin/paper/cate/save',
                                delete:'/exam-admin/paper/cate/delete',
                                tree:'/exam-admin/paper/cate/tree'
                                }"
            :current="current"
          />
          <paper-cate
            ref="paperCate"
            v-if="isMonth"
            :setCurrent="setCurrent"
            :url="{
                                update:'/exam-admin/daily/cate/update',
                                save:'/exam-admin/daily/cate/save',
                                delete:'/exam-admin/daily/cate/delete',
                                tree:'/exam-admin/daily/cate/tree'
                                }"
            :current="current"
          />
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
          </div>
        </el-dialog>
      </el-header>
      <el-main v-if="form.quesRange === 0 && isMonth">
        <div class="kxy-paper">
          <el-alert type="info">
            <template slot="title">
              <p style="margin: 0;display: flex;align-items: flex-start;padding-right: 5px">
                <span style="width: 35px">提示:</span>
                <span style="flex: 1">请选择指定的题库</span>
              </p>
            </template>
          </el-alert>
          <el-tree
            ref="tree"
            :data="dataList"
            node-key="id"
            show-checkbox
            highlight-current
            :default-expanded-keys="[]"
            :default-checked-keys="quesCateIds"
            accordion
            @check-change="changeTree"
            draggable
          >
            <div class="custom-tree-node" slot-scope="{node, data}" @mouseup="mouseup($event,node,data)">
              <div class="custom-tree-node-box">
                <div style="margin-left: 20px">
                  <img v-if="data.parentId >= 0" width="20" height="20" src="/static/img/user/dept.png"/>
                  <img v-else width="20" height="20" src="/static/img/user/dept-group.png"/>
                  <!--<input type="text" :value="node.label" @change="modify($event,data)"/>-->
                </div>
                <div class="label">{{data.name}}</div>
                <div class="actions"></div>
              </div>
            </div>
          </el-tree>
        </div>
      </el-main>
      <!-- ref="addExamMain"   :style="{'height':addExamMain}"  -->
      <!--     -->
      <!--      v-if="form.radio == 2"-->
      <el-main ref="addExamMain" style="height: 800px">
        <div v-if="form.quesRange === 1 || !isMonth">
          <el-tooltip class="item" effect="dark" content="管理员自由选择试题组建成一套试卷" placement="top-start">
            <el-button
              type="primary"
              round
              style="margin-bottom: 10px"
              @click="openSelectTopic"
              v-if="modify === 'No' || parseInt(modify) === 0"
              :disabled="selectButton[0] || noEdit"
            >选题组卷
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="根据抽取规则简单、正常、困难，抽取一定数量的题目组建成一套试卷"
            placement="top-start"
          >
            <el-button
              type="primary"
              round
              style="margin-bottom: 10px"
              @click="openTopic(1)"
              v-if="modify === 'No' || parseInt(modify) === 1"
              :disabled="selectButton[1] || noEdit"
            >抽题组卷
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="根据抽取规则，随机抽取一定数量的题目组成试题卷，相比前两个组卷方式，随机组卷的特点是每个用户拿到的试卷都不一样"
            placement="top-start"
          >
            <el-button
              type="primary"
              round
              style="margin-bottom: 10px"
              @click="openTopic(2)"
              v-if="modify === 'No' || parseInt(modify) === 2"
              :disabled="selectButton[2] || noEdit"
            >随机组卷
            </el-button>
          </el-tooltip>
          <table border="0" cellpadding="10" cellspacing="0" width="100%" class="add-exam-table">
            <tr align="left">
              <th>类型</th>
              <th>单选</th>
              <th>多选</th>
              <th>判断</th>
              <th>填空</th>
              <th>简答</th>
              <!--
                                      <th>排序</th>
              <th>填空</th>-->
              <th>共计</th>
            </tr>
            <tr>
              <th align="left">数量</th>
              <td class="add-exam-table-bg">{{oddTotalTopic}}</td>
              <td class="add-exam-table-bg">{{manyTotalTopic}}</td>
              <td class="add-exam-table-bg">{{judgeTotalTopic}}</td>
              <td class="add-exam-table-bg">{{backTotalTopic}}</td>
              <td class="add-exam-table-bg">{{shortTopic}}</td>
              <!--
                                      <td class="add-exam-table-bg">&#45;&#45;</td>
              <td class="add-exam-table-bg">&#45;&#45;</td>-->
              <td class="add-exam-table-bg">{{oddTotalTopic + manyTotalTopic + judgeTotalTopic + backTotalTopic + shortTopic}}</td>
            </tr>
            <tr v-if="!isMonth">
              <th align="left">分数</th>
              <td class="add-exam-table-bg">{{oddTotalScore}}</td>
              <td class="add-exam-table-bg">{{manyTotalScore}}</td>
              <td class="add-exam-table-bg">{{judgeTotalScore}}</td>
              <td class="add-exam-table-bg">{{backTotalScore}}</td>
              <td class="add-exam-table-bg">{{shortscore}}</td>
              <!--
                                      <td class="add-exam-table-bg">&#45;&#45;</td>
              <td class="add-exam-table-bg">&#45;&#45;</td>-->
              <td class="add-exam-table-bg">{{oddTotalScore + judgeTotalScore + manyTotalScore + backTotalScore + shortscore}}</td>
            </tr>
          </table>
        </div>
          <!-- 选择试题 -->
          <div style="height: 400px">
            <selectTopic
              ref="selectTopic"
              v-show="isSelectTopic"
              :examData="examData"
              :setExamData="setExamData"
              :quesDisorder="form.quesDisorder"
              :setQuesDisorder="setQuesDisorder"
            />
            <topic ref="topic" v-show="isTopic" :setTopic="setTopic" :isMonth="isMonth"/>
            <div
              class="add-exam-box"
              v-show="parseInt(this.compType) === 0"
              style="height: 600px"
            >
              <!--          :style="{'height':addExamSelect}"-->
              <div class="add-exam-fraction">
                <ul>
                  <li
                    v-for="(val,key) in examData"
                    :key="key"
                    @click="goAnchor(`#mao_${key}`)"
                    v-show="val.length"
                  >
                    <h3>
                      <template v-if="parseInt(key) === 1">单选题</template>
                      <template v-else-if="parseInt(key) === 2">多选题</template>
                      <template v-else-if="parseInt(key) === 3">判断题</template>
                      <template v-else-if="parseInt(key) === 4">填空题</template>
                      <template v-else>简答题</template>
                    </h3>
                    <el-form :inline="true">
                      <el-form-item label="每题分数:" v-if="!isMonth">
                        <template v-if="parseInt(key) === 1">
                          <el-input-number
                            type="number"
                            v-model="oddFraction"
                            :min="0"
                            :precision="0"
                            @change="changeFraction($event,key)"
                          />
                        </template>
                        <template v-else-if="parseInt(key) === 2">
                          <el-input-number
                            type="number"
                            v-model="manyFraction"
                            :min="0"
                            :precision="0"
                            @change="changeFraction($event,key)"
                          />
                        </template>
                        <template v-else-if="parseInt(key) === 3">
                          <el-input-number
                            type="number"
                            v-model="judgeFraction"
                            :min="0"
                            :precision="0"
                            @change="changeFraction($event,key)"
                          />
                        </template>
                        <template v-else-if="parseInt(key) === 4">
                          <el-input-number
                            type="number"
                            v-model="backFraction"
                            :min="0"
                            :precision="0"
                            @change="changeFraction($event,key)"
                          />
                        </template>
                        <template v-else>
                          <el-input-number
                            type="number"
                            v-model="shortFraction"
                            :min="0"
                            :precision="0"
                            @change="changeFraction($event,key)"
                          />
                        </template>
                      </el-form-item>
                    </el-form>
                  </li>
                </ul>
              </div>
              <div class="add-exam-list-box">
                <ul
                  :id="`mao_${key}`"
                  class="add-exam-list"
                  v-for="(val,key) in examData"
                  :key="key"
                  v-show="val.length"
                >
                  <template v-if="val.length">
                    <li v-for="(x,i) in val" :key="x.id">
                      <template v-if="x.exist">
                        <h3>
                          <span v-if="parseInt(key) === 1">单选题</span>
                          <span v-else-if="parseInt(key) === 2">多选题</span>
                          <span v-else-if="parseInt(key) === 3">判断题</span>
                          <span v-else-if="parseInt(key) === 5">简答题</span>
                          <span v-else>填空</span>
                          <div v-if="!isMonth">
                            <p>
                              题目分数：
                              <input
                                type="number"
                                @change="scoreChange($event,key,i)"
                                v-model="x.score"
                              />
                            </p>
                          </div>
                        </h3>
                        <h6 v-html="x.info"></h6>
                        <ul>
                          <li v-for="i in x.questionOptionEntities" :key="i.key">
                            {{i.key}}.
                            {{i.option}}
                          </li>
                        </ul>
                        <p>标准答案: {{x.answ}}</p>
                        <div class="add-exam-list-analysis" v-if="x.analysis">
                          <p>试题解析:</p>
                          <p>{{x.analysis}}</p>
                        </div>
                        <div class="add-exam-list-difficult">
                          <div>
                            <span>难易度：</span>
                            <template v-if="parseInt(x.level) === 0">简单</template>
                            <template v-else-if="parseInt(x.level) === 1">一般</template>
                            <template v-else>困难</template>
                          </div>
                          <div>
                            <el-button
                              type="info"
                              class="el-icon-top"
                              @click="_up(val,i)"
                              :disabled="noEdit"
                              circle
                            />
                            <el-button
                              type="info"
                              class="el-icon-bottom"
                              @click="_down(val,i)"
                              :disabled="noEdit"
                              circle
                            />
                            <el-button
                              type="danger"
                              icon="el-icon-delete"
                              @click="_delect(val,i,key)"
                              :disabled="noEdit"
                              circle
                            />
                          </div>
                        </div>
                      </template>
                      <template v-else>
                        <h3 style="color: #F56C6C">该试题已被删除</h3>
                        <div class="add-exam-list-difficult">
                          <div>
                            <span>难易度：</span>
                            <template v-if="parseInt(x.level) === 0">简单</template>
                            <template v-else-if="parseInt(x.level) === 1">一般</template>
                            <template v-else>困难</template>
                          </div>
                          <div>
                            <el-button type="info" class="el-icon-top" @click="_up(val,i)" circle/>
                            <el-button type="info" class="el-icon-bottom" @click="_down(val,i)" circle/>
                            <el-button
                              type="danger"
                              icon="el-icon-delete"
                              @click="_delect(val,i,key)"
                              circle
                            />
                          </div>
                        </div>
                      </template>
                    </li>
                  </template>
                </ul>
              </div>
            </div>
          </div>
      </el-main>
    </el-container>
  </el-drawer>
</template>

<script>
  /* eslint-disable */
  import {goAnchor} from './../../utils'
  import selectTopic from './selectTopic'
  import topic from './topic'
  import paperCate from './../../views/modules/paper/papercate'
  /* eslint-disable */
  export default {
    name: 'addExam',
    props: {
      testType: Number,
      isMonth: {
        type: Boolean,
        default: false
      },
      getDataList: {
        type: Function,
        default: function () {
          return _ => ({})
        }
      },
      setExamRow: {
        type: Function,
        default: function () {
          return _ => ({})
        }
      },
      setExam: {
        type: Function,
        default: function () {
          return _ => ({})
        }
      },
      getExam: {
        type: Function,
        default: function () {
          return _ => ({})
        }
      },
      url: {
        type: Object,
        default: _ => ({
          info: `/exam-admin/paper/info`,
          save: `/exam-admin/paper/save`,
          update: `/exam-admin/paper/update`
        })
      }
    },
    components: {selectTopic, paperCate, topic},
    data() {
      return {
        selectButton: [false, false, false],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now()
          }
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        noEdit: false,
        _select: [],
        quesCateIds: [],
        dataList: [],
        addExamMain: '500px',
        addExamSelect: '0px',
        loading: false,
        compType: null,
        modify: 'No',
        allTopicNum: {},
        topicArr: [],
        quesType: 0,
        dialogFormVisible: false,
        isSelectTopic: false,
        isTopic: false,
        isRandomTopic: false,
        paperId: null,
        current: {},
        paperCate: false,
        oddTotalScore: 0,
        manyTotalScore: 0,
        judgeTotalScore: 0,
        shortscore: 0,
        backTotalScore: 0,
        oddTotalTopic: 0,
        backTotalTopic: 0,
        manyTotalTopic: 0,
        judgeTotalTopic: 0,
        shortTopic: 0,
        oddFraction: null,
        manyFraction: null,
        judgeFraction: null,
        backFraction: null,
        shortFraction: null,
        shortion: null,
        formLabelWidth: '120px',
        examDialogVisible: false,
        checked: false,
        form: {
          name: '',
          cateId: '',
          date: [],
          startTime: '',
          endTime: '',
          judge: 0,
          ischecked: false,
          answType: 1,
          quesRange: 0,
          isTimeRange: 0,
          everyTimeAnswNum: 1,
          answUpperLimit: 1,
          intervalDay: 1,
          quesDisorder: 0,
          dailyQuesCount: 1
        },
        rules: {
          name: [{required: true, message: '请输入试卷名称', trigger: 'blur'}],
          cateId: [
            {required: true, message: '请选择试卷分类', trigger: 'blur'}
          ]
        },
        examData: {} /* 选择的题的数据 */,
        examTotal: [] /* 统一选择的题的总数 */,
        /* 每日一题复用参数-start */
        daily: {
          status: false,
          publisherType: '',
          examType: 0,
          setUserList: []
        },
        noEdit: null
        /* 每日一题复用参数-end */
      }
    },
    methods: {
      setQuesDisorder(val) {
        this.form.quesDisorder = val
      },
      changeTime(val) {
        if (val != true) {
          this.form.quesRange = 0
        }
      },
      change(val) {
      },
      changeTree(data, checked) {
        console.log(checked)
        if (data.children.length > 0) {
          data.children.forEach(item => {
            this.changeTree(item, checked)
          })
        }
        if (checked) {
          if(this.quesCateIds.indexOf(data.id) === -1) {
            this.quesCateIds.push(data.id)
          }
        } else {
          let index = this.quesCateIds.indexOf(data.id)
          index > -1 && this.quesCateIds.splice(index, 1)
        }
      },
      mouseup(e, node, data) {
        this.that_data = data
        this.that_node = node
        if (e.button === 2) {
          if (e.y > document.body.clientHeight / 2) {
            this.paperList = {
              display: 'block',
              bottom: `${document.body.clientHeight - e.clientY}px`,
              left: `${e.clientX}px`
            }
          } else {
            this.paperList = {
              display: 'block',
              top: `${e.clientY}px`,
              left: `${e.clientX}px`
            }
          }
        } else {
          this.paperList.display = 'none'
        }
      },
      init(id, noEdit, type) {
        if (id && type !== 3) {
          this.form.judge = 1
        }
        this.getTree()
        this.noEdit = noEdit
        this.selectButton = this.selectButton.map(x => false)
        this.allTopicNum = {}
        this.modify = 'No'
        if (this.testType && parseInt(this.testType) === 2) {
          this.modify = 2
        }
        this.paperId = null
        this.quesCateIds = []
        this.form = {
          name: '',
          cateId: '',
          date: [],
          judge: 0,
          answType: 1,
          intervalDay: 1,
          quesRange: 0,
          ischecked: false,
          isTimeRange: 0,
          quesDisorder: 0,
          everyTimeAnswNum: 1,
          answUpperLimit: 1,
          dailyQuesCount: 1
        }
        this.current = {}
        this.examDialogVisible = true
        this.daily = {
          status: false,
          publisherType: '',
          examType: 0,
          setUserList: []
        }
        this.oddTotalScore = 0
        this.manyTotalScore = 0
        this.judgeTotalScore = 0
        this.shortscore = 0
        this.backTotalScore = 0
        this.oddTotalTopic = 0
        this.backTotalTopic = 0
        this.manyTotalTopic = 0
        this.judgeTotalTopic = 0
        this.shortTopic = 0
        this.examData = {}
        this.compType = null
        // this.$nextTick(_ => {
        //   let height =
        //     document.body.clientHeight - this.$refs.addExamMain.$el.offsetTop
        //   this.addExamMain = `${height}px`
        //   this.addExamSelect = `${height - 190}px`
        // })
        if (id) {
          this.loading = true
          this.$http({
            url: this.$http.adornUrl(`${this.url.info}/${id}`),
            method: 'post'
          })
            .then(res => {
              if (parseInt(res.code) === 200) {
                this.modify = res.data.compType
                if (this.testType && this.testType === 2) {
                  this.modify = 2
                }
                this.compType = res.data.compType
                this.paperId = res.data.id
                this.form = {
                  name: res.data.paperName,
                  cateId: res.data.cateId,
                  // date: `${res.data.year}-${res.data.month}`,
                  date: res.data.endTime != null ? [res.data.startTime, res.data.endTime] : [],
                  quesDisorder: res.data.quesDisorder || 0,
                  publisherType: res.data.publisherType,
                  compType: res.data.compType,
                  everyTimeAnswNum: res.data.everyTimeAnswNum,
                  answUpperLimit: res.data.answUpperLimit,
                  answType: res.data.answType,
                  intervalDay: res.data.intervalDay,
                  isTimeRange: res.data.isTimeRange,
                  quesRange: res.data.quesRange,
                  ischecked: res.data.quesRange === 1
                }
                this.quesCateIds = res.data.quesCateIdList ? res.data.quesCateIdList : []

                if (res.data.quesRange === 0) {
                  this.examData = {}
                  this.oddTotalScore = 0
                  this.manyTotalScore = 0
                  this.judgeTotalScore = 0
                  this.shortscore = 0
                  this.backTotalScore = 0
                }
                this.current.name = res.data.cateName
                this.daily = {
                  status: this.noEdit
                    ? parseInt(res.data.publisherType) !== 0
                    : false,
                  publisherType: this.noEdit
                    ? parseInt(res.data.publisherType) === 0
                      ? 'noEdit'
                      : 'edit'
                    : '',
                  examType: res.data.publisherType,
                  setUserList: res.data.userInfoEntities
                }
                if (parseInt(res.data.compType) === 0) {
                  this.examData = {
                    '1': res.data.singerChoiceqstEntities || [],
                    '2': res.data.multiChoiceqstEntities || [],
                    '3': res.data.judgeqstEntities || [],
                    '4': res.data.fillBlacksQuesBanks || [],
                    '5': res.data.qaquesBanks || []
                  }
                  this._switch()
                } else {
                  let paperInfo = JSON.parse(res.data.paperInfo)
                  this.allTopicNum = {}
                  if (Object.keys(paperInfo).length) {
                    for (let key in paperInfo) {
                      this.allTopicNum[paperInfo[key].cateId] = {
                        odd: {},
                        many: {},
                        judge: {},
                        back: {},
                        short: {}
                      }
                    }
                    for (let _key in this.allTopicNum) {
                      for (let key in paperInfo) {
                        if (parseInt(paperInfo[key].cateId) === parseInt(_key)) {
                          switch (parseInt(paperInfo[key].quesType)) {
                            case 1:
                              this.allTopicNum[_key].odd = paperInfo[key]
                              break
                            case 2:
                              this.allTopicNum[_key].many = paperInfo[key]
                              break
                            default:
                              this.allTopicNum[_key].judge = paperInfo[key]
                          }
                        }
                      }
                    }
                    this.setTopic(this.allTopicNum)
                  }
                }
                this.loading = false
              }
            })
            .catch(_ => {
              this.loading = false
            })
        }
      },
      async getTree() {
        let res = await this.$http.post('/exam-admin/ques/cate/tree')
        this.dataList = res.data
      },
      setCurrent(data) {
        if (data.id) {
          this.current = data
          this.form.cateId = data.id
          this.$nextTick(_ => this.$refs['form'].validateField('cateId'))
        }
      },
      checkSort() {
        this.dialogFormVisible = true
        this.paperCate = true
        this.$nextTick(() => {
          this.$refs.paperCate.init()
        })
      },
      // 试卷分类
      checkSort() {
        this.dialogFormVisible = true
        this.paperCate = true
        this.$nextTick(() => {
          this.$refs.paperCate.init()
        })
      },
      goAnchor,
      _switch(key) {
        if (key) {
          switch (parseInt(key)) {
            case 1:
              // eslint-disable-next-line no-eval
              this.oddTotalScore = this.examData[key].length
                ? eval(
                  this.examData[key].map(x => (x.score ? x.score : 0)).join('+')
                )
                : 0
              this.oddTotalTopic = this.examData[key].length || 0
              let isOddTrue
              this.examData[key].forEach((x, i, arr) => {
                isOddTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isOddTrue = null
                  return false
                }
              })
              if (isOddTrue) {
                this.oddFraction = isOddTrue
              } else {
                this.oddFraction = null
              }
              break
            case 2:
              // eslint-disable-next-line no-eval
              this.manyTotalScore = this.examData[key].length
                ? eval(
                  this.examData[key].map(x => (x.score ? x.score : 0)).join('+')
                )
                : 0
              this.manyTotalTopic = this.examData[key].length || 0
              let isManyTrue
              this.examData[key].forEach((x, i, arr) => {
                isManyTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isManyTrue = null
                  return false
                }
              })
              if (isManyTrue) {
                this.manyFraction = isManyTrue
              } else {
                this.manyFraction = null
              }
              break
            case 3:
              // eslint-disable-next-line no-eval
              this.judgeTotalScore = this.examData[key].length || 0
                ? eval(
                  this.examData[key].map(x => (x.score ? x.score : 0)).join('+')
                )
                : 0
              this.judgeTotalTopic = this.examData[key].length || 0
              let isJudgeTrue
              this.examData[key].forEach((x, i, arr) => {
                isJudgeTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isJudgeTrue = null
                  return false
                }
              })
              if (isJudgeTrue) {
                this.judgeFraction = isJudgeTrue
              } else {
                this.judgeFraction = null
              }
              break
            case 5:
              // eslint-disable-next-line no-eval
              this.shortscore = this.examData[key].length || 0
                ? eval(
                  this.examData[key].map(x => (x.score ? x.score : 0)).join('+')
                )
                : 0
              this.shortTopic = this.examData[key].length || 0
              let isShortTrue
              this.examData[key].forEach((x, i, arr) => {
                isShortTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isShortTrue = null
                  return false
                }
              })
              if (isShortTrue) {
                this.shortFraction = isShortTrue
              } else {
                this.shortFraction = null
              }
              break
            default:
              // eslint-disable-next-line no-eval
              this.backTotalScore = this.examData[key].length
                ? eval(
                  this.examData[key].map(x => (x.score ? x.score : 0)).join('+')
                )
                : 0
              this.backTotalTopic = this.examData[key].length || 0
              let isBackTrue
              this.examData[key].forEach((x, i, arr) => {
                isBackTrue = arr[0].score
                if (x.score !== arr[0].score) {
                  isBackTrue = null
                  return false
                }
              })
              if (isBackTrue) {
                this.backFraction = isBackTrue
              } else {
                this.backFraction = null
              }
              break
          }
        } else {
          if (Object.keys(this.examData).length) {
            for (let key in this.examData) {
              this._switch(key)
            }
          }
        }
      },
      changeFraction(val, key) {
        this.examData[key].forEach(x => {
          x.score = val || 1
        })
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        this._switch(key)
      },
      scoreChange(e, key, i) {
        this.examData[key][i].score = e.target.value || 1
        this._switch(key)
        switch (parseInt(key)) {
          case 1:
            this.oddFraction = null
            break
          case 2:
            this.manyFraction = null
            break
          case 3:
            this.judgeFraction = null
            break
          case 4:
            this.backFraction = null
            break
          default:
            this.shortion = null
            break
        }
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
      },
      openSelectTopic() {
        this.selectButton = this.selectButton.map(x => true)
        this.selectButton[0] = false
        this.isTopic = false
        this.topicArr = []
        this.compType = 0
        this.isSelectTopic = true
        // if (!Object.keys(this.examData).length) {
        //   this.examData = JSON.parse(sessionStorage.getItem('examData') || '{}')
        // }
        this._switch()
        this.$nextTick(_ => {
          this.$refs.selectTopic.init(this.examData)
        })
      },
      openTopic(id) {
        this.selectButton = this.selectButton.map(x => true)
        this.selectButton[id] = false
        if (this.compType && this.compType != id) {
          // sessionStorage.removeItem('topic')
          this.allTopicNum = {}
        }
        this.isSelectTopic = false
        this.examData = {}
        this.compType = id
        this.isTopic = true
        // this.topicArr = JSON.parse(sessionStorage.getItem('topic') || '[]')
        this.getTopic()
        this.$nextTick(_ => {
          this.$refs.topic.init(this.allTopicNum, id)
        })
      },
      onSubmit() {
        this.quesIds = this.quesCateIds.map(x => x).join(',')
        let data = []
        this.$refs['form'].validate(valid => {
          if (valid) {
            // if (this.compType === '') {
            //   return this.$notify.error({
            //     title: '错误',
            //     message: '试题为空，不能添加'
            //   })
            // }
            if (parseInt(this.compType) === 0) {
              if (!Object.keys(this.examData).length) {
                return this.$notify.error({
                  title: '错误',
                  message: '试题为空，不能添加'
                })
              }
              for (let key in this.examData) {
                data = data.concat(this.examData[key])
              }
              data = data.map(x => ({
                id: x.id,
                score: x.score,
                quesType: x.quesType
              }))
            }
            // if (parseInt(this.compType) === 0 || this.dataForm.quesRange) {
            //   if (!Object.keys(this.examData).length) {
            //     return this.$notify.error({
            //       title: '错误',
            //       message: '试题为空，不能添加'
            //     })
            //   }
            //   for (let key in this.examData) {
            //     data = data.concat(this.examData[key])
            //   }
            //   data = data.map(x => ({
            //     id: x.id,
            //     score: x.score,
            //     quesType: x.quesType
            //   }))
            // }
            if (parseInt(this.compType) === 1 || parseInt(this.compType) === 2) {
              if (!this.topicArr.length) {
                return this.$notify.error({
                  title: '错误',
                  message: '试题为空，不能添加'
                })
              }
              data = JSON.parse(JSON.stringify(this.topicArr))
              data = data.map(x => {
                delete x['totalTopic']
                return x
              })
            }
            this.loading = true
            let _data = {
              paperName: this.form.name,
              cateId: this.form.cateId,
              startTime: this.form.date[0],
              endTime: this.form.date[1],
              everyTimeAnswNum: this.form.everyTimeAnswNum,
              answUpperLimit: this.form.answUpperLimit,
              answType: this.form.answType,
              quesRange: this.form.quesRange,
              isTimeRange: this.form.ischecked === true ? 1 : 0,
              intervalDay: this.form.answType === 4 ? this.form.intervalDay : 0,
              dailyQuesCount: this.form.dailyQuesCount,
              paperInfo: JSON.stringify(data),
              compType: this.compType,
              quesCateIds: this.quesIds,
              totalper: `${this.oddTotalScore +
              this.manyTotalScore +
              this.judgeTotalScore + this.backTotalScore + this.shortscore}`
            }
            if (parseInt(this.compType) === 0)
              _data = Object.assign(_data, {
                quesDisorder: this.form.quesDisorder
              })
            if (this.paperId) _data = Object.assign(_data, {id: this.paperId})
            // 每日一题获取数据
            if (this.isMonth) {
              this.getExam(
                Object.assign(_data, {date: this.form.date}, this.daily),
                this.noEdit
              )
              this.loading = false
              return false
            }
            // if (parseInt(this.modify) === 2 && this.testType === 2) {
            //   console.log('parseInt(this.modify) === 2 && this.testType === 2')
            //   this.setExamRow({
            //     paperInfo: JSON.stringify(data),
            //     paperName: this.form.name,
            //     id: null
            //   })
            //   this.setExam()
            //   this.loading = false
            //   return false
            // }
            this.$http({
              url: this.$http.adornUrl(
                this.paperId ? this.url.update : this.url.save
              ),
              method: 'post',
              data: _data
            })
              .then(res => {
                if (res && res.code === 200) {
                  this.$message.success('操作成功')
                  // parseInt(this.compType) === 0
                  //   ? sessionStorage.removeItem('examData')
                  //   : sessionStorage.removeItem('topic')
                  this.examData = {}
                  if (res.data) {
                    this.setExamRow({
                      id: res.data.id,
                      paperName: res.data.paperName
                    })
                  }
                  this.getDataList()
                  this.setExam()
                  this.examDialogVisible = false
                } else {
                  this.$message.warning(res.msg)
                }
                this.loading = false
              })
              .catch(_ => {
                this.loading = false
              })
          }
        })
      },
      setExamData(data) {
        this.examData = data
        // sessionStorage.setItem('examData', JSON.stringify(data))
        this._switch()
        this.$forceUpdate()
      },
      setTopic(data) {
        console.log(data)
        this.topicArr = []
        if (Object.keys(data).length) {
          for (let key in data) {
            for (let _key in data[key]) {
              data[key][_key].totalTopic = null
              if (Object.keys(data[key][_key]).length > 1) {
                for (let _key_ in data[key][_key]) {
                  if (_key_.substr(-3) === 'Num') {
                    data[key][_key].totalTopic += parseFloat(
                      data[key][_key][_key_]
                    )
                  }
                }
                this.topicArr.push(data[key][_key])
              }
            }
          }
        }
        // sessionStorage.setItem('topic', JSON.stringify(this.topicArr))
        this.getTopic()
        this.$forceUpdate()
      },
      getTopic() {
        let arr1 = this.topicArr.filter(x => parseInt(x.quesType) === 1)
        let arr2 = this.topicArr.filter(x => parseInt(x.quesType) === 2)
        let arr3 = this.topicArr.filter(x => parseInt(x.quesType) === 3)
        let arr4 = this.topicArr.filter(x => parseInt(x.quesType) === 4)
        let arr5 = this.topicArr.filter(x => parseInt(x.quesType) === 5)
        if (arr1.length) {
          var oddTotalTopic = 0
          arr1.forEach(x => {
            oddTotalTopic += x.totalTopic
          })
          this.oddTotalScore = oddTotalTopic * arr1[0].score
          this.oddTotalTopic = oddTotalTopic
        } else {
          this.oddTotalTopic = 0
          this.oddTotalScore = 0
        }
        if (arr2.length) {
          var manyTotalTopic = 0
          arr2.forEach(x => {
            manyTotalTopic += x.totalTopic
          })
          this.manyTotalScore = manyTotalTopic * arr2[0].score
          this.manyTotalTopic = manyTotalTopic
        } else {
          this.manyTotalTopic = 0
          this.manyTotalScore = 0
        }
        if (arr3.length) {
          var judgeTotalTopic = 0
          arr3.forEach(x => {
            judgeTotalTopic += x.totalTopic
          })
          this.judgeTotalScore = judgeTotalTopic * arr3[0].score
          this.judgeTotalTopic = judgeTotalTopic
        } else {
          this.judgeTotalTopic = 0
          this.judgeTotalScore = 0
        }
        if (arr4.length) {
          var backTotalTopic = 0
          arr4.forEach(x => {
            backTotalTopic += x.totalTopic
          })
          this.backTotalScore = backTotalTopic * arr4[0].score
          this.backTotalTopic = backTotalTopic
        }
        if (arr5.length) {
          var shortTopic = 0
          arr5.forEach(x => {
            shortTopic += x.totalTopic
          })
          this.shortscore = shortTopic * arr5[0].score
          this.shortTopic = shortTopic
        }else {
          this.shortTopic = 0
          this.shortscore = 0
        }
      },
      // 两个元素交换位置
      swapArray(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      },
      _up(arr, i) {
        if (parseInt(i) !== 0) {
          this.swapArray(arr, i - 1, i)
          // sessionStorage.setItem('examData', JSON.stringify(this.examData))
          this.$forceUpdate()
        } else {
          this.$message.warning('已经处于置顶，无法上移')
        }
      },
      _down(arr, i) {
        if (parseInt(i) !== arr.length - 1) {
          this.swapArray(arr, i, i + 1)
          // sessionStorage.setItem('examData', JSON.stringify(this.examData))
          this.$forceUpdate()
        } else {
          this.$message.warning('已经处于置底，无法下移')
        }
      },
      _delect(arr, i, key) {
        arr.splice(i, 1)
        // sessionStorage.setItem('examData', JSON.stringify(this.examData))
        this._switch(key)
      }
    }
  }
</script>

<style lang="scss">
  .exam-drawer-box {
    #el-drawer__title {
      display: none;
    }
  }

  .kxy-paper {
    position: relative;
    min-width: 270px;
    width: 500px;
    height: 100%;
    overflow: auto;
    border: 1px solid #ebeef5;

    .el-tree-node__content {
      height: 32px;
    }

    .custom-tree-node {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      /*input {*/
      /*    border: 0;*/
      /*    padding: 2px 5px;*/
      /*    font-size: 14px;*
      /*    width: 85px;*/
      /*    height: 20px;*/
      /*    line-height: 16px;*/
      /*}*/

      .custom-tree-node-box {
        display: flex;
        flex: 1;
        align-items: center;

        .label {
          margin-left: 12px;
          line-height: 20px;
          width: 250px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        .actions {
          display: flex;
          flex: 1;
          margin-left: 10px;
          justify-content: flex-end;

          .action-item {
            height: 20px;
            width: 20px;
            margin-right: 6px;
          }

          .el-button--text {
            font-size: 13px;
            color: #606266;
          }
        }
      }
    }
  }

  .add-exam-box {
    padding-top: 20px;
    display: flex;
    justify-content: space-between;

    .add-exam-fraction {
      padding: 10px 50px 10px 0;
      width: 300px;

      ul {
        margin: 0;
        padding: 0;
        list-style-type: none;

        li {
          margin-bottom: 50px;
          padding: 10px 20px;
          border-radius: 5px;
          box-shadow: 2px 2px 5px #333333;
          cursor: pointer;
        }
      }
    }

    .add-exam-list-box {
      flex: 1;
      /*overflow: auto;*/
      /*border: 1px solid #ebeef5;*/
    }
  }

  .add-exam-table {
    font-size: 12px;
    font-weight: 300;

    th {
      font-weight: 300;
      background: #e9eef1;
      border: 1px solid #eee;
    }

    td {
      border-width: 0 1px 1px;
      border-color: #eee;
      border-style: solid;
    }
  }

  .add-exam-list {
    &:first-of-type {
      margin: 0;
    }

    margin: 10px 0 0;
    list-style-type: none;
    padding: 20px;
    background: #e9e9eb;

    li {
      margin: 10px;
      padding: 20px 30px;
      background: white;
      font-size: 12px;
      color: #72767b;

      h3,
      h6 {
        margin: 0;
      }

      h3 {
        color: #333;
        padding: 10px 0;
        font-size: 16px;
        display: flex;
        justify-content: space-between;

        p {
          font-weight: 400;
          margin: 0;
        }
      }

      h6 {
        padding-left: 5px;
        font-size: 14px;
        font-weight: 400;
      }

      ul {
        padding: 10px;
        list-style: none;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        li {
          margin: 0;
          padding: 5px 10px;
          width: 50%;
        }
      }

      .add-exam-list-analysis {
        display: flex;
        padding: 10px 0;

        p {
          margin: 0;
        }

        p:last-of-type {
          flex: 1;
          height: 40px;
          border: 1px solid #72767b;
          margin: 0 5px 0 30px;
          padding: 5px;
        }
      }

      .add-exam-list-difficult {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;

        div:first-of-type {
          display: flex;
          align-items: center;

          p {
            margin: 0 10px;
            padding: 10px;
            border: 1px solid #72767b;
          }
        }
      }
    }
  }
</style>
